<template>
  <div class="container">
    <el-tag style="float: left; margin-top: 5px; margin-left: 15px" v-if="form.remark != ''">{{ form.remark }}</el-tag>
    <el-form ref="form" :model="form" :rules="rules" label-width="80px" hidden>
      <el-form-item label="表单名" prop="form">
        <el-input v-model="form.name" placeholder="请输入表单名" />
      </el-form-item>
      <el-form-item label="开启状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio v-for="dict in dict.type.form_status" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input type="textarea" v-model="form.remark" placeholder="请输入备注" />
      </el-form-item>
    </el-form>

    <div class="center-full">
      <div class="action-bar">
        <el-button icon="el-icon-monitor" type="text" @click="handleDetail">查看</el-button>
        <el-button icon="el-icon-check" type="text" @click="save">保存</el-button>
        <el-button class="copy-btn-main" icon="el-icon-close" style="color: red" type="text" @click="close"> 关闭</el-button>
      </div>

      <!-- 中间，表单项 -->
      <el-scrollbar class="center-scrollbar">
        <parser :table-info="tableInfoDatat" :form-info="formConf" :dict-ex="dictEx"></parser>
      </el-scrollbar>
      <div v-show="!tableInfoDatat.show" class="empty-info">请绑定数据库，添加字段</div>
    </div>

    <!-- 右边：组件属性/表单属性 -->
    <right-panel
      :table-info="tableInfoDatat"
      :is-sub="isSubA"
      :op-tabel="opTabel"
      :form-info="form"
      :form-conf="formConf"
      @fetch-data="fetchData"
      @form-conf-change="formNameChage"
      @remark-form="remarkForm"
      @op-tabel-fun="opTabelChange"
      @op-find-field-fun="opFindFieldFun"
      @field-info-submit="fieldInfoSubmit"
      @form-id-change="formIdChange"
    />
  </div>
</template>

<script>
import Parser from '@/views/bpm/table/Parser'
import tableJs from '@/components/generator/table'
import { listTablePro } from '@/api/business/tableInfo'
import RightPanel from '@/views/tool/build/RightPanelTable'
import { createForm, getForm, updateForm } from '@/api/bpm/table'
//============
import { debounce } from 'throttle-debounce'

import { formConf } from '@/components/generator/config'
import { deepCloneForm, isObjectObject } from '@/utils/index'
import drawingDefalut from '@/components/generator/drawingDefalut'
import logo from '@/assets/logo/logo.png'
// import Parser from '@/components/parser/Parser'
import { saveDrawingList, getIdGlobal, saveIdGlobal, saveOpTabel } from '@/utils/db'
import loadBeautifier from '@/utils/loadBeautifier'
import { CommonStatusEnum } from '@/utils/constants'
import bus from '@/api/eventBus.js'
import { decodeFields } from '@/utils/formGenerator'
import { getDicts } from '@/api/system/dict/data'
const idGlobal = getIdGlobal()
let oldActiveId
export default {
  dicts: ['form_status'],
  components: {
    Parser,
    RightPanel
  },
  data() {
    return {
      dictEx: {},
      findField: [],
      tableJs,
      isSubA: true,
      logo,
      idGlobal,
      formConf,
      opTabel: [],

      activeId: drawingDefalut[0].__config__.formId,
      drawingList: [], // 表单项的数组
      // 表单详情
      detailOpen: false,
      detailForm: {
        fields: []
      },
      //==========
      tableInfoDatat: {},
      ch: tableJs.__config__.children[0],
      //==========
      formData: {},

      activeData: drawingDefalut[0], // 右边编辑器激活的表单项
      saveDrawingListDebounce: debounce(340, saveDrawingList),
      saveIdGlobalDebounce: debounce(340, saveIdGlobal),
      // 表单参数
      form: {
        status: CommonStatusEnum.ENABLE
      },
      // 表单校验
      rules: {
        name: [{ required: true, message: '表单名不能为空', trigger: 'blur' }],
        status: [{ required: true, message: '开启状态不能为空', trigger: 'blur' }]
      }
    }
  },
  computed: {},
  watch: {
    formConf: {
      handler(val) {
        if (this.isSubA) {
          this.databaseChange(val)
        }
      },
      deep: true
    },
    activeId: {
      handler(val) {
        oldActiveId = val
      },
      immediate: true
    },
    drawingList: {
      handler(val) {
        this.saveDrawingListDebounce(val)
        if (val.length === 0) this.idGlobal = 100
      },
      deep: true
    },
    idGlobal: {
      handler(val) {
        this.saveIdGlobalDebounce(val)
      },
      immediate: true
    }
  },
  mounted() {
    loadBeautifier((btf) => {
      beautifier = btf
    })
  },
  created() {
    // 读取表单配置
    const formId = this.$route.query && this.$route.query.formId
    if (formId) {
      this.isSubA = false
      getForm(formId).then((response) => {
        const data = response.data
        this.form = {
          id: data.id,
          formId: data.formId,
          name: data.name,
          status: data.status,
          remark: data.remark
        }
        this.formConf = JSON.parse(data.conf)
        this.drawingList = decodeFields(data.fields)
        // 设置激活的表单项
        this.tableInfoDatat = this.drawingList[0]
        this.activeId = this.activeData.__config__.formId
        // 设置 idGlobal，避免重复
        this.idGlobal += this.drawingList.length

        for (var index in this.tableInfoDatat.children) {
          if (this.tableInfoDatat.children[index].show) {
            this.opTabel = [...this.opTabel, this.tableInfoDatat.children[index].label]
          }
        }

        for (var index in this.tableInfoDatat.queryParams) {
          if (this.tableInfoDatat.queryParams[index].status) {
            this.findField = [...this.findField, this.tableInfoDatat.queryParams[index].label]
          }
        }
        var len = this.tableInfoDatat.children.length

        for (let index = 0; index < len; index++) {
          if (this.tableInfoDatat.children[index].__config__.dict != '') {
            getDicts(this.tableInfoDatat.children[index].__config__.dict).then((response) => {
              var dictOne = {}
              for (let index = 0; index < response.data.length; index++) {
                dictOne[response.data[index].dictValue] = [response.data[index].dictLabel, response.data[index].listClass]
              }
              this.dictEx[response.data[0].dictType] = dictOne
            })
          }
        }

        bus.$emit('share', this.opTabel)
        bus.$emit('shareField', this.findField)
        bus.$emit('share', this.opTabel)
        bus.$emit('tablename', this.tableInfoDatat.tableName)
        bus.$emit('formId', this.form.formId)
      })
    } else {
      this.isSubA = true
    }
  },
  methods: {
    formIdChange(val) {
      this.form.formId = val
    },
    fieldInfoSubmit(val) {
      this.tableInfoDatat.children[val.id].label
      this.tableInfoDatat.children[val.id].show
      this.tableInfoDatat.children[val.id].__config__.dict
      this.tableInfoDatat.children[val.id].__config__.width
    },
    databaseChange(val) {
      listTablePro().then((response) => {
        response.rows.map((item) => {
          if (item.tableName == val.formRef) {
            this.getTableData(item)
            this.tableInfoDatat = { ...this.tableInfoDatat, ...{ tableName: item.tableName } }
          }
        })
      })
    },
    opFindFieldFun(val) {
      this.findField = val

      for (var index in this.tableInfoDatat.queryParams) {
        this.tableInfoDatat.queryParams[index].status = false
      }
      for (let index = 0; index < val.length; index++) {
        for (var sign in this.tableInfoDatat.queryParams) {
          if (val[index] == this.tableInfoDatat.queryParams[sign].label) {
            this.tableInfoDatat.queryParams[sign].status = true
          }
        }
      }
    },
    opTabelChange(val) {
      this.opTabel = val
      if (val.length > 0) {
        this.tableInfoDatat.show = true
      } else {
        this.tableInfoDatat.show = false
      }
      for (var index in this.tableInfoDatat.children) {
        this.tableInfoDatat.children[index].show = false
      }
      for (let index = 0; index < val.length; index++) {
        for (var sign in this.tableInfoDatat.children) {
          if (val[index] == this.tableInfoDatat.children[sign].label) {
            this.tableInfoDatat.children[sign].show = true
          }
        }
      }
    },
    // contains(arr, val) {
    //   return arr.some((item) => item === val)
    // },
    getTableData(item) {
      const qu = JSON.parse(JSON.stringify(this.tableJs.__config__.queryParams))

      this.tableInfoDatat = { ...this.tableInfoDatat, ...{ show: false } }
      this.tableInfoDatat = { ...this.tableInfoDatat, ...{ queryParams: [] } }
      const op = JSON.parse(JSON.stringify(this.tableJs.__config__.operate))
      op.map((item) => {
        setTimeout(() => {
          item.key += new Date().getTime()
        }, 10)
      })

      this.tableInfoDatat = {
        ...this.tableInfoDatat,
        ...{
          operate: op
        }
      }

      const opc = JSON.parse(JSON.stringify(this.tableJs.__config__.opCol))
      opc.map((item) => {
        setTimeout(() => {
          item.key += new Date().getTime()
        }, 10)
      })

      this.tableInfoDatat = {
        ...this.tableInfoDatat,
        ...{
          opCol: opc
        }
      }
      this.tableInfoDatat = { ...this.tableInfoDatat, ...{ children: [] } }
      for (let index = 0; index < item.columns.length; index++) {
        setTimeout(() => {
          this.ch.show = false
          this.ch.label = item.columns[index].columnComment
          this.ch.key += new Date().getTime()
          this.ch.prop = item.columns[index].javaField
          this.ch.__config__.dict = ''
          this.ch.__config__.width = 150
          this.tableInfoDatat.children.push(JSON.parse(JSON.stringify(this.ch)))
        }, 10)

        qu[0].key += new Date().getTime()
        qu[0].prop = item.columns[index].javaField
        qu[0].label = item.columns[index].columnComment
        this.tableInfoDatat.queryParams = [...this.tableInfoDatat.queryParams, ...[JSON.parse(JSON.stringify(qu[0]))]]
      }
    },

    /** 详情按钮操作 */
    handleDetail() {
      getForm(this.form.id).then((response) => {
        // 设置值
        const data = response.data
        this.detailForm = {
          ...JSON.parse(data.conf),
          fields: decodeFields(data.fields)
        }
        // 弹窗打开
        this.detailOpen = true
      })
    },
    remarkForm(val) {
      this.form.remark = val
    },
    formNameChage(val) {
      if (val.disabled) {
        this.form.status = '1'
      } else {
        this.form.status = '0'
      }
      this.form.name = val.formRef
      //
    },
    setObjectValueReduce(obj, strKeys, data) {
      const arr = strKeys.split('.')
      arr.reduce((pre, item, i) => {
        if (arr.length === i + 1) {
          pre[item] = data
        } else if (!isObjectObject(pre[item])) {
          pre[item] = {}
        }
        return pre[item]
      }, obj)
    },
    setRespData(component, resp) {
      const { dataPath, renderKey, dataConsumer } = component.__config__
      if (!dataPath || !dataConsumer) return
      const respData = dataPath.split('.').reduce((pre, item) => pre[item], resp)

      // 将请求回来的数据，赋值到指定属性。
      // 以el-tabel为例，根据Element文档，应该将数据赋值给el-tabel的data属性，所以dataConsumer的值应为'data';
      // 此时赋值代码可写成 component[dataConsumer] = respData；
      // 但为支持更深层级的赋值（如：dataConsumer的值为'options.data'）,使用setObjectValueReduce
      this.setObjectValueReduce(component, dataConsumer, respData)
      const i = this.drawingList.findIndex((item) => item.__config__.renderKey === renderKey)
      if (i > -1) this.$set(this.drawingList, i, component)
    },
    fetchData(component) {
      const { dataType, method, url } = component.__config__
      if (dataType === 'dynamic' && method && url) {
        this.setLoading(component, true)
        this.$axios({
          method,
          url
        }).then((resp) => {
          this.setLoading(component, false)
          this.setRespData(component, resp.data)
        })
      }
    },
    setLoading(component, val) {
      const { directives } = component
      if (Array.isArray(directives)) {
        const t = directives.find((d) => d.name === 'loading')
        if (t) t.value = val
      }
    },
    // 获得表单数据
    AssembleFormData() {
      this.formData = {
        fields: deepCloneForm(this.drawingList),
        ...this.formConf
      }
    },
    save() {
      this.$refs['form'].validate((valid) => {
        if (!valid) {
          return
        }
        const form = {
          conf: JSON.stringify(this.formConf), // 表单配置
          fields: this.encodeFields(), // 表单项的数组
          ...this.form // 表单名等
        }
        if (this.formConf == '' || this.formConf == undefined) {
          this.$message({
            message: '亲,您忘记给人家取名字了😘~',
            type: 'warning'
          })
          return
        }

        //修改的提交
        if (this.form.id != null) {
          updateForm(form).then((response) => {
            this.$modal.msgSuccess('修改成功')
            this.close()
          })
          return
        }
        if (this.form.remark == '' || this.form.remark == undefined) {
          this.$message.error('亲,您忘记给人家起名字了😘~~')
        } else {
          // 添加的提交
          createForm(form).then((response) => {
            this.$modal.msgSuccess('新增成功')
            this.close()
          })
        }
      })
    },
    /** 关闭按钮 */
    close() {
      this.$tab.closeOpenPage({ path: '/bpm/table' })
    },
    encodeFields() {
      var fields = []
      fields = [...[JSON.stringify(this.tableInfoDatat)], ...fields]
      return fields
    }
  }
}
</script>

<style lang="scss">
@import '@/styles/home';
</style>
